package cn.dazhou.railway.client

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.content.pm.PackageManager
import android.os.Bundle
import android.os.IBinder
import android.util.Log
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import cn.dazhou.railway.bindremoteservice.IDzEngine
import cn.dazhou.railway.client.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity(), ServiceConnection {

    private val binding by lazy { ActivityMainBinding.inflate(layoutInflater) }
    private var dzEngine: IDzEngine? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        binding.bind.setOnClickListener { bind() }
        binding.unbind.setOnClickListener { unbind() }
        binding.call.setOnClickListener { call() }
        binding.send.setOnClickListener { sendBroadcast() }
    }

    private fun sendBroadcast() {
        val intent = Intent("com.example.action.MY_CUSTOM_ACTION")
        intent.setPackage("cn.dazhou.railway.bindremoteservice")
        // 适配被停止应用接收
        intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
        sendBroadcast(intent)
    }

    private fun call() {
        Log.i("ABCD", dzEngine?.hello("Even") ?: "dzEngine=null")
    }

    private fun bind() {
        val intent = Intent("cn.android666.remoteservice.hahaha")
        intent.setPackage("cn.dazhou.railway.bindremoteservice")
//        intent.setComponent(ComponentName("cn.dazhou.railway.bindremoteservice", "cn.dazhou.railway.bindremoteservice.RemoteService"))
        val resolveInfo = packageManager.resolveService(intent, PackageManager.MATCH_ALL)
        Log.d("ABCD", "可绑定的服务：${resolveInfo?.serviceInfo?.name ?: "无"}")
        val result = bindService(intent, this, Context.BIND_AUTO_CREATE)
        Log.i("ABCD", "绑定函数返回结果：$result")
    }

    private fun unbind() {
        val intent = Intent("cn.android666.remoteservice.hahaha")
        intent.setPackage("cn.dazhou.railway.bindremoteservice")
//        intent.setComponent(ComponentName("cn.dazhou.railway.bindremoteservice", "cn.dazhou.railway.bindremoteservice.RemoteService"))
        unbindService(this)
    }

    /** 在与 Service 的连接建立时调用 */
    override fun onServiceConnected(name: ComponentName, service: IBinder) {
        dzEngine = IDzEngine.Stub.asInterface(service)
        val hello = dzEngine?.hello("张三")
        Log.i("ABCD","远程服务绑定成功: $hello")
    }

    /** 当与服务的连接被意外中断时执行，这通常发生在服务的进程崩溃或被终止时。 */
    override fun onServiceDisconnected(name: ComponentName) {
        Log.i("ABCD","远程服务的连接被意外中断")
        dzEngine = null
    }
}